/**
 * 提供文字、图片、语音、视频、图文切换的tab指令
 */
define(function (require, exports, module) {
    var angular = require('angular');
    var util = require('util');

    var module = angular.module('directives.sendTab', ['services.dialog','direcitves.emotion','ngPublicUI']);
    module.factory('sendTabService',['$rootScope','http','imgDialogService','voiceDialogService','videoDialogService',function($rootScope,http,imgDialogService,voiceDialogService,videoDialogService){

        var DEFAULT_SEND_TYPE = 'text';

        var DEFAULT_CURR_MEDIA = {
            showDiv : false,
            type : 0,
            sendType : '',
            media_id : '',
            url : '',
            name : '',
            content : ''
        };
        var initMedias = function(){
            return {
                'text' : $.extend({},DEFAULT_CURR_MEDIA,{type:1,sendType:'text'}),
                'imageText' : $.extend({},DEFAULT_CURR_MEDIA,{type:2,sendType:'imageText'}),
                'voice' : $.extend({},DEFAULT_CURR_MEDIA,{type:3,sendType:'voice'}),
                'image' : $.extend({},DEFAULT_CURR_MEDIA,{type:4,sendType:'image'}),
                'video' : $.extend({},DEFAULT_CURR_MEDIA,{type:5,sendType:'video'})
            }
        }


        var obj = {};

        obj.medias = initMedias();

        obj.sendType = DEFAULT_SEND_TYPE;////当前发送类型: 文字text|图片image|语音voice|视频video

        obj.currMedia = obj.medias[DEFAULT_SEND_TYPE];

        obj.emotionShow = false;

        obj.previewEmotionSrc = '';

        obj.imgDialog = imgDialogService;

        obj.voiceDialog = voiceDialogService;

        obj.videoDialog = videoDialogService;

        obj.uploaderOptions = {
            success : function(ret){
                if(obj.sendType == 'image'){
                    obj.addImage(ret);
                }else if(obj.sendType == 'voice'){
                    obj.addVoice(ret);
                }else if(obj.sendType == 'video'){
                    obj.addVideo(ret);
                }
            }
        }

        obj.getTypeMap = function(type){
            // 1文字，2图文，3语音，4图片, 5视频
            if(typeof(type)=='string'){
                if(type == 'text'){
                    return 1;
                }else if (type == 'image'){
                    return 4;
                }else if(type == 'voice'){
                    return 3;
                }else if(type == 'video'){
                    return 5;
                }
            }else if(typeof(type)=='number'){
                if(type == 1){
                    return 'text';
                }else if (4){
                    return 'image';
                }else if(type == 3){
                    return 'voice';
                }else if(type == 5){
                    return 'video';
                }
            }
        }


        obj.initTab = function(data){
            obj.medias = initMedias();
            if(data){
                var tempType = obj.getTypeMap(parseInt(data.type)) || DEFAULT_SEND_TYPE;
                obj.changeSendType(tempType);
                obj.initCurrMedia(data);
            }else{
                obj.changeSendType(DEFAULT_SEND_TYPE);
                obj.currMedia = $.extend({},DEFAULT_CURR_MEDIA,{type:1,sendType:DEFAULT_SEND_TYPE});
            }

        }
        obj.getCurrType = function(){
            return obj.currMedia.type;
        }
        obj.getCurrContent = function(){
            var content,currMedia = obj.currMedia;
            if(currMedia.sendType=='text'){
                content = $('.emotion_editor .edit_area').html();
            }else{
                content = {
                    media_id : currMedia.media_id,
                    img_url : currMedia.img_url,
                    name : currMedia.name
                }
            }
            return content;
        }


        obj.changeSendType = function(send){
            obj.sendType = send;
            obj.currMedia = obj.medias[send];
        }

        obj.initCurrMedia = function(data){
            if(data){
                var tempType = obj.getTypeMap(parseInt(data.type));
                if(tempType!='text'){
                    var content = angular.fromJson(data.content);
                    obj.currMedia.showDiv = true;
                    obj.currMedia.sendType = tempType;
                    obj.currMedia.media_id = content.media_id;
                    obj.currMedia.url = content.url;
                    obj.currMedia.name = content.name;
                }else{
                    $('.emotion_editor .edit_area').html(data.content);
                }
            }
        }
        obj.resetContent = function(){
            if(obj.sendType == 'text'){
                $('.emotion_editor .edit_area').html('');
            }
            obj.currMedia = angular.copy(DEFAULT_CURR_MEDIA);
        }

        return obj;
    }]);

    module.directive('sendTab', [
        '$compile','$rootScope','$location','http','limit','sendTabService',
        function ($compile,$rootScope,$location,http,limit,sendTabService) {
            return {
                restrict : "A",
                replace :true,
                //scope : {
                //
                //},
                templateUrl: 'js/directives/send_tab/send_tab.html',
                link: function (scope, element, attr,ctl) {

                    scope.sendTab = scope.$parent.sendTab  = sendTabService;

                    scope.addImage = function(data){
                        var picture = data;
                        scope.imageMedia.type = 4 ;
                        scope.imageMedia.content = angular.copy(picture);
                        scope.imageMedia.url = picture.img_url;
                        scope.imageMedia.name = picture.name;
                    };

                    scope.addVoice = function(voice){
                        scope.voiceMedia.type = 3 ;
                        scope.voiceMedia.content = angular.copy(voice);
                        scope.voiceMedia.url = voice.voice_url;
                        scope.voiceMedia.name = voice.name;
                    };

                    scope.addVideo = function(video){
                        scope.videoMedia.type = 5;
                        scope.videoMedia.content = angular.copy(video);
                        scope.videoMedia.url = video.video_url;
                        scope.videoMedia.name = video.title;
                    };
                    scope.addImageText = function(imageText){
                        scope.imageTextMedia.type = 2;
                        scope.imageTextMedia.content = angular.copy(imageText);
                    }

                    scope.messageSelector = {
                        init: function ($dialogScope,$dialog) {
                            $dialogScope.messageSelector = scope.messageSelector;
                            scope.dialog = $dialog;
                            scope.searchMessageList(1);
                        },
                        create: function ($dialog) {
                            scope.dialog.close();
                            $location.path('/material/img_text/edit');
                        },
                        selected: undefined,
                        select: function (index) {
                            scope.messageSelector.selected = index;
                        },
                        search: {
                            keyword: "",
                            reset: function () {
                                scope.messageSelector.search.keyword = "";
                            },
                            submit: function () {
                                scope.searchMessageList(1,scope.messageSelector.search.keyword);
                            }
                        },
                        add: function () {
                            var selected = scope.messageSelector.selected;
                            if (selected !== undefined) {
                                scope.message = scope.messageSelector.messageList[selected];
                                scope.addImageText(scope.message);
                            }
                        },
                        pagination : {
                            pages : 0,
                            current : 1,
                            change: function (page) {
                                scope.messageSelector.selected = undefined;
                                scope.searchMessageList(page);
                            }
                        }
                    };
                    scope.searchMessageList = function (page,keyword) {
                        http.get('material/mpnews-list',{
                            keyword: keyword || "",
                            limit: limit,
                            offset: limit * (page - 1)
                        })
                        .success(function (res) {
                            if (res.result || res.retCode == 0) {
                                scope.messageSelector.messageList = res.data.data;
                                scope.messageSelector.pagination.pages = Math.ceil(res.data.total / limit);
                                return;
                            }
                                $rootScope.$emit('httpRequestFail','获取图文消息失败');
                        })
                        .error(function (res) {
                                $rootScope.$emit('httpRequestFail','获取图文消息失败');
                        });
                    };

                    scope.init = function(){
                        scope.textMedia = {
                            type : 1,
                            content : '',
                            max : 600
                        };
                        scope.imageTextMedia = {
                            type : 2,
                            content : ''
                        };
                        scope.voiceMedia = {
                            type : 3,
                            content : ''
                        };
                        scope.imageMedia = {
                            type : 4,
                            content : ''
                        };
                        scope.videoMedia = {
                            type : 5,
                            content : ''
                        };
                        scope.currMedia = scope.textMedia;
                    }
                    scope.$watch('textMedia.content',function(newValue){
                        if(newValue){
                            scope.textMedia.remain = scope.textMedia.max - newValue.replace(/<img.*?[\/]{0,1}>/g,'111').length;//一个图片占3个长度
                            $('.js_textArea .editor_tip em').text(scope.textMedia.remain);
                        }
                    })


                    /**
                     * 清空数据
                     * @param mediaName
                     */
                    scope.clear = function(mediaName){
                        scope.currMedia = scope[mediaName] = {};
                    };

                    /**
                     * 文本回复内容改变事件
                     * @param $event
                     */

                    scope.bindChangeEvent = function(){
                        $('.js_textArea .edit_area')
                            .on('input',function(){
                                var html = $(this).html();
                                scope.textMedia.content = html;
                                scope.textMedia.remain = scope.textMedia.max - html.replace(/<img.*?[\/]{0,1}>/g,'111').length;//一个图片占3个长度
                                $('.js_textArea .editor_tip em').text(scope.textMedia.remain);
                                // fixme : 这里不能使用$apply,否则编辑框关标会移位
                                //scope.$apply();
                            })
                    }

                    scope.initTab = function(data){
                        scope.init();

                        if(!data){
                            return ;
                        }
                        // 1文字，2图文，3语音，4图片, 5视频
                        switch (data.type){
                            case '1' :
                                scope.textMedia.type = data.type;
                                scope.textMedia.content = data.content;
                                scope.currMedia = scope.textMedia;
                                break;
                            case '2' :
                                var content = angular.fromJson(data.content);
                                scope.message = content;
                                scope.imageTextMedia = {
                                    type : data.type,
                                    content : data.content
                                };
                                scope.currMedia = scope.imageTextMedia;
                                break;
                            case '3' :
                                var content = angular.fromJson(data.content);
                                scope.voiceMedia = {
                                    type : data.type,
                                    content : data.content,
                                    url : content.voice_url,
                                    name : content.name
                                }
                                scope.currMedia = scope.voiceMedia;
                                break;
                            case '4' :
                                var content = angular.fromJson(data.content);
                                scope.imageMedia = {
                                    type : data.type,
                                    content : data.content,
                                    url : content.img_url,
                                    name : content.name
                                }
                                scope.currMedia = scope.imageMedia;
                                break;
                            case '5' :
                                var content = angular.fromJson(data.content);
                                scope.videoMedia = {
                                    type : data.type,
                                    content : data.content,
                                    url : content.video_url,
                                    name : content.name
                                }
                                scope.currMedia = scope.videoMedia;
                                break;
                            default :
                        }
                    };
                    scope.$on('initTab',function(event,data){
                        scope.initTab(data);
                    });

                    scope.$on('tabData',function(event){
                        if(scope.currMedia.content){
                            scope.$emit('giveTabData',scope.currMedia);
                        }else{
                            util.notify('内容不能为空！');
                        }

                    });

                    scope.$emit('tabLinkEnd');
                }
            };
        }
    ]);

});